package com.example.springbootwebadmin.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * 文件上传测试
 */
@Controller
public class FormTestController {
    @GetMapping("/form_layouts")
    public String form_layouts(){
        return "/form/form_layouts";
    }

    /**
     * MultipartFile自动封装上传过来的文件
     * @param email
     * @param username
     * @param headerImg
     * @param photos
     * @return
     */
    @PostMapping("/upload")
    public String upload(@RequestParam String email,
                         @RequestParam String username,
                         @RequestPart("headerImg") MultipartFile headerImg,
                         @RequestPart("photos") MultipartFile[] photos
    ) throws Exception{
        if(!headerImg.isEmpty()){
            String originalFilename = headerImg.getOriginalFilename();
            headerImg.transferTo(new File("D:\\Temp\\"+originalFilename));
        }
        if(photos.length>0){
            for (MultipartFile file : photos) {
                if (!file.isEmpty()){
                    String originalFilename = file.getOriginalFilename();
                    System.out.println("file = " + file.getName());
                    file.transferTo(new File("D:\\Temp\\"+originalFilename));
                }
            }
        }

        return "index";
    }
}
